import { InterfaceFile } from '@/api/interface/basic/file';
import { BasicForm } from '@/components/ProForm/interface';
import { PublicInterface } from '@/interface/public';

export interface FileDataProps {
  suffix: 'pdfSuffix' | 'imgSuffix' | 'acceptSuffix';
}

export const useFile = (addFileForm: BasicForm<InterfaceFile.ReqUploadFile>, fileRef: PublicInterface.ProTableValue) => {
  let fileObj = ref({
    // 上传参数
    uploadingData: {
      remark: ''
    },
    fileList: [],
    headers: {
      TOKEN: useUserStore().token
    },
    maxSize: 10485760,
    acceptSuffix: '.jpeg,.png,.jpg,.txt,.doc,.docx,.xls,.xlsx,.pdf',
    imgSuffix: ['.jpeg', '.png', '.jpg'],
    // 文档格式
    pdfSuffix: ['.pdf']
  });

  const getSuffix = (fileName: string) => {
    const key = fileName.lastIndexOf('.');
    const nameLength = fileName.length;
    const fileSuffix = fileName.substring(key, nameLength);
    return fileSuffix;
  };

  /**
   * 格式验证
   */
  const verificationFormat = (row: InterfaceFile.ResFileList, key: FileDataProps['suffix']) => {
    const { fileName } = row || {};
    if (!fileName) return false;
    return fileObj.value[key].includes(getSuffix(fileName));
  };

  /** 上传文件 */
  const onChange = (file: any, fileList: any) => {
    fileObj.value.fileList = fileList;
    if (fileList?.length) {
      const { name } = fileList[0];

      const key = name.indexOf('.');
      const _name = name.substring(0, key);
      // 获取文件名称
      Object.assign(addFileForm.form, {
        fileName: !addFileForm.form.fileName ? _name : addFileForm.form.fileName
      });
    }
  };

  /** 文件上传个数验证提示 */
  const onExceed = () => {
    elMessage('一次只能上传一个文件', 'warning');
  };

  /** 上传成功操作 */
  const onSuccess = () => {
    fileRef.value?.search();
    addFileForm.visible = false;
    elMessage();
  };

  /**上传前验证 */
  const fileBeforeUpload = (file: any) => {
    const { name, size } = file || {};
    const key = name.lastIndexOf('.');
    const nameLength = name.length;
    // 可接受的文件类型
    const accept = fileObj.value.acceptSuffix.split(',');
    const fileSuffix = name.substring(key, nameLength);
    if (!accept.includes(fileSuffix)) {
      elMessage(`只能上传${fileObj.value.acceptSuffix}类型文件`, 'warning');
      return false;
    }

    if (size > fileObj.value.maxSize) {
      elMessage('上传数据不能大于10M', 'warning');
      return false;
    }
  };

  return { fileObj, verificationFormat, onChange, fileBeforeUpload, onSuccess, onExceed };
};
